﻿/*
Copyright (c) 2025 HeZongLun
NahidaProject is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan
PSL v2.
You may obtain a copy of Mulan PSL v2 at:
		 http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/

#pragma once

#include <string>
#include <map>
#include <filesystem>
#include <iostream>
#include <fstream>

#ifdef _WIN32
#define ExportSymbol  __declspec(dllexport)
#else
#define ExportSymbol
#endif

namespace NahidaProject {
	class ExportSymbol StaticWebServer {
	public:
		struct ExportSymbol StaticWebServerHTTPRequest {
			std::string method;
			std::string url;
			std::string version;
			std::map<std::string, std::string> headers;
		};

		StaticWebServer(int port, const std::string& rootDirectory);
		~StaticWebServer();

		void StartServer();
		void StopServer();

	private:
		int port;
		std::string rootDirectory;
		int serverSocket;
		bool running;

		void HandleClient(int clientSocket);
		std::string ReadRequest(int clientSocket);
		StaticWebServerHTTPRequest ParseRequest(const std::string& request);
		void HandleGetRequest(int clientSocket, const StaticWebServerHTTPRequest& request);
		void SendFile(int clientSocket, const std::filesystem::path& file_path, bool headOnly);
		void SendDirectoryListing(int clientSocket, const std::filesystem::path& directoryPath);
		void SendErrorResponse(int clientSocket, int status_code, const std::string& message);
		std::string GetMimeType(const std::string& extension);
		void Cleanup();
	};
}
